package com.zx.callback.common.utils;

import com.alibaba.fastjson.JSON;
import com.zx.callback.common.utils.baidu.LocationIpResultVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

/**
 *
 * 类描述：baidu Map
 * 作者		yanst
 * 创建时间：	2015-5-19 下午6:28:56
 */
@Component("baiduMapUtil")
public class BaiduMapUtil {
	private String baiduMapAk;
	private String baiduMapSk;
	private String baiduMapMainUrl;
	private String baiduMapMethodUrl;

	private BaiduMapUtil(){}

	@Value("#{propertiesReader['baidu.map.ak']}")
	private void setBaiduMapAk(String baiduMapAk) {
		this.baiduMapAk = baiduMapAk;
	}

	@Value("#{propertiesReader['baidu.map.sk']}")
	private void setBaiduMapSk(String baiduMapSk) {
		this.baiduMapSk = baiduMapSk;
	}

	@Value("#{propertiesReader['baidu.map.main.url']}")
	private void setBaiduMapMainUrl(String baiduMapMainUrl) {
		this.baiduMapMainUrl = baiduMapMainUrl;
	}

	@Value("#{propertiesReader['baidu.map.method.url']}")
	private void setBaiduMapMethodUrl(String baiduMapMethodUrl) {
		this.baiduMapMethodUrl = baiduMapMethodUrl;
	}



	/**
	 * 根据坐标进行逆地理编码服务
	 * @return
	 * @throws Exception
	 */
	public LocationIpResultVO ipGetCityInfo() throws Exception{
		return ipGetCityInfo("");
	}

	/**
	 * 根据坐标进行逆地理编码服务
	 * @param ip  纬度
	 * @return
	 * @throws Exception
	 */
	public LocationIpResultVO ipGetCityInfo(String ip)
			throws Exception {
		Map paramsMap = new LinkedHashMap<String, String>();
		paramsMap.put("ip", ip);
		paramsMap.put("ak", baiduMapAk);
		paramsMap.put("coor", "bd09ll");
		String paramsStr = toQueryString(paramsMap);

		//根据ak 获取sn
		StringBuffer wholeStr = new StringBuffer();
		wholeStr.append(baiduMapMethodUrl);
		wholeStr.append("?");
		wholeStr.append(paramsStr);
		wholeStr.append(baiduMapSk);
		String tempStr = URLEncoder.encode(wholeStr.toString(), "UTF-8");
		String sn = MD5(tempStr);

		//拼装请求的url
		StringBuffer url = new StringBuffer();
		url.append(baiduMapMainUrl+baiduMapMethodUrl);
		url.append("?");
		url.append(paramsStr);
		url.append("&sn=");
		url.append(sn);
		String json = loadJSON(url.toString());
		return JSON.parseObject(json, LocationIpResultVO.class);
	}

	//调用百度接口
	private String loadJSON (String baiduUrl) {
		StringBuffer strBuf;
		strBuf = new StringBuffer();
		try{
			URL url = new URL(baiduUrl);
			URLConnection conn = url.openConnection();
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));//转码。
			String line = null;
			while ((line = reader.readLine()) != null)
				strBuf.append(line + " ");
			reader.close();
		}catch(IOException e){
			e.printStackTrace();
		}

		return strBuf.toString();
	}

	// 对Map内所有value作utf8编码，拼接返回结果
	private String toQueryString(Map<?, ?> data) throws UnsupportedEncodingException {
		StringBuffer queryString = new StringBuffer();
		for (Entry<?, ?> pair : data.entrySet()) {
			queryString.append(pair.getKey() + "=");
			queryString.append(pair.getValue()+ "&");

		}
		if (queryString.length() > 0) {
			queryString.deleteCharAt(queryString.length() - 1);
		}
		return queryString.toString();
	}

	//来自stackoverflow的MD5计算方法，调用了MessageDigest库函数，并把byte数组结果转换成16进制
	private String MD5(String md5) {
		try {
			java.security.MessageDigest md = java.security.MessageDigest
					.getInstance("MD5");
			byte[] array = md.digest(md5.getBytes());
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < array.length; ++i) {
				sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100)
						.substring(1, 3));
			}
			return sb.toString();
		} catch (java.security.NoSuchAlgorithmException e) {
		}
		return null;
	}

	public static void main(String[] args) {
		try {
//			ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"classpath:config/spring/spring-application-context.xml"});
//			context.start();
//			BaiduUtil baiduUtil = (BaiduUtil) context.getBean("baiduUtil"); // 获取远程服务代理
			BaiduMapUtil baiduUtil1 = new BaiduMapUtil();
			System.out.println(com.alibaba.fastjson.JSON.toJSONString(baiduUtil1.ipGetCityInfo()));

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
